package com.credithc.customers.manager.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.credithc.customers.base.codes.CustomerCodes;
import com.credithc.customers.base.exception.CustomerException;
import com.credithc.customers.base.mapper.CustUnifyLoginStatisticMapper;
import com.credithc.customers.base.mapper.CustUnifyRegisterStatisticMapper;
import com.credithc.customers.base.po.CustUnifyLoginStatisticPo;
import com.credithc.customers.base.po.CustUnifyRegisterStatisticPo;
import com.credithc.customers.base.po.SystemInfoPo;
import com.credithc.customers.base.ro.CountLoginFlowRo;
import com.credithc.customers.base.service.ICacheService;
import com.credithc.customers.base.service.ICommonService;
import com.credithc.customers.base.utils.ClassUtils;
import com.credithc.customers.base.utils.CustomerUtils;
import com.credithc.customers.manager.service.IStatisticPushService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Title: 数据统计
 * @Author: fby
 * @Date: 2020/03/24 10:21
 * @Description: com.credithc.customers.manager.service.impl
 * @Version: V1.0.0
 */
@Service
@Slf4j
public class StaticsicPushServiceImpl implements IStatisticPushService {
    @Autowired
    private CustUnifyLoginStatisticMapper loginStatisticMapper;
    @Autowired
    private CustUnifyRegisterStatisticMapper registerStatisticMapper;
    @Autowired
    private ICommonService commonService;
    @Autowired
    private ICacheService cacheService;

    @Override
    public JSONObject countRegister(CountLoginFlowRo ro) {
        JSONObject data = new JSONObject();
        String productCode = ro.getProductCode();
        String cycle = ro.getCycle();
        String subSystemSign = null;
        //获取productCode对应系统标识
        if (StringUtils.isNotBlank(productCode) && (!"operation".equalsIgnoreCase(productCode))) {
            SystemInfoPo systemInfoPo = commonService.getSystemInfo(productCode);
            if (systemInfoPo == null) {
                log.error("一账通数据统计异常：对应产品不存在");
                return data;
            } else {
                subSystemSign = systemInfoPo.getSystemSign();
            }

        }
        data.put("productCode", productCode);
        data.put("productId", ro.getProductId());
        //todo 需求变更，改为统计前一天0-24点，当天9点推送数据
        String currentDay = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesterDay;
//        String currentDayTime = currentDay + " 00:00:00";
//        if (!CustomerUtils.isPastDate(currentDayTime)) {
//            currentDay = CustomerUtils.getPastDate(1, currentDay);
//            currentDayTime = currentDay + " 13:00:00";
//        }
        String yesterDayTime = CustomerUtils.getPastDate(1, currentDay) + " 00:00:00";
        String currentDayTime = CustomerUtils.getPastDate(1, currentDay) + " 23:59:59";
        if (StringUtils.isNotBlank(cycle)) {
            if ("day".equals(cycle)) {
                yesterDay = CustomerUtils.getPastDate(1, currentDay);
            } else if ("week".equals(cycle)) {
                yesterDay = CustomerUtils.getPastDate(7, currentDay);
            } else if ("month".equals(cycle)) {
                yesterDay = CustomerUtils.getPastDate(30, currentDay);
            } else {
                yesterDay = CustomerUtils.getPastDate(1, currentDay);
            }
        } else {
            yesterDay = CustomerUtils.getPastDate(1, currentDay);
        }
        List<CustUnifyRegisterStatisticPo> pos = new ArrayList<>();
        List<CustUnifyRegisterStatisticPo> posc = new ArrayList<>();
        List<CustUnifyRegisterStatisticPo> poSum = new ArrayList<>();
        List<CustUnifyRegisterStatisticPo> poSum1 = new ArrayList<>();


        if (StringUtils.isNotBlank(productCode)) {
            if ("operation".equalsIgnoreCase(productCode)) {
                pos = registerStatisticMapper.getRegisterStatistic(currentDay, yesterDay, null);
                poSum = registerStatisticMapper.getRegisterStatisticSum(currentDay, yesterDay, null);
            } else if ("BDSHC".equals(subSystemSign) || "BDSHM".equals(subSystemSign)) {
                pos = registerStatisticMapper.getRegisterStatistic(currentDay, yesterDay, "BDSHM");
                posc = registerStatisticMapper.getRegisterStatistic(currentDay, yesterDay, "BDSHC");
                poSum = registerStatisticMapper.getRegisterStatisticSum(currentDay, yesterDay, "BDSHM");
                poSum1 = registerStatisticMapper.getRegisterStatisticSum(currentDay, yesterDay, "BDSHC");
            } else {
                pos = registerStatisticMapper.getRegisterStatistic(currentDay, yesterDay, subSystemSign);
                poSum = registerStatisticMapper.getRegisterStatisticSum(currentDay, yesterDay, subSystemSign);
            }
        } else {
            //查询所有
            pos = registerStatisticMapper.getRegisterStatistic(currentDay, yesterDay, null);
            poSum = registerStatisticMapper.getRegisterStatisticSum(currentDay, yesterDay, null);
        }
        pos.addAll(posc);
        JSONArray tables = new JSONArray();
        JSONObject table = new JSONObject();
        table.put("tableKey", "countType");
        table.put("tableName", "用户注册信息分段(按小时)统计(" + yesterDayTime + "--" + currentDayTime + ")");
        table.put("columns", "系统名称,统计区间(1小时内),新注册用户数,新授权登录数,新授权注册数");
        if (pos != null && pos.size() > 0) {
            List<List<Object>> dataList = new ArrayList<>();
            for (CustUnifyRegisterStatisticPo registerStatisticPo : pos) {
                List<Object> objectList = new ArrayList<>();
                String systemName = cacheService.getSystemNameBySign(registerStatisticPo.getSubSystemSign());
                objectList.add(systemName);
                objectList.add(registerStatisticPo.getHour());
                objectList.add(registerStatisticPo.getRegisterNum());
                objectList.add(registerStatisticPo.getAuthLoginNum());
                objectList.add(registerStatisticPo.getAuthRegisterNum());
//                Integer registerSum = getRegisterSum(registerStatisticPo.getSubSystemSign(), currentDay);
//                objectList.add(registerSum);
                dataList.add(objectList);
            }
            table.put("list", dataList);
            tables.add(table);
        }

        JSONObject table1 = new JSONObject();
        table1.put("tableKey", "countType1");
        table1.put("tableName", "用户注册信息累计(按天)统计(" + yesterDayTime + "--" + currentDayTime + ")");
        table1.put("columns", "系统名称,新注册用户数,新授权登录数,新授权注册数,累计注册总数");
        poSum.addAll(poSum1);
        if (poSum != null && poSum.size() > 0) {
            List<List<Object>> dataList = new ArrayList<>();
            for (CustUnifyRegisterStatisticPo registerStatisticPo : poSum) {
                List<Object> objectList = new ArrayList<>();
                String systemName = cacheService.getSystemNameBySign(registerStatisticPo.getSubSystemSign());
                objectList.add(systemName);
                objectList.add(registerStatisticPo.getRegisterNum());
                objectList.add(registerStatisticPo.getAuthLoginNum());
                objectList.add(registerStatisticPo.getAuthRegisterNum());
                objectList.add(registerStatisticPo.getTotalNum());
//                Integer registerSum = getRegisterSum(registerStatisticPo.getSubSystemSign(), currentDay);
//                objectList.add(registerSum);
                dataList.add(objectList);
            }
            table1.put("list", dataList);
            tables.add(table1);
        }
        data.put("tables", tables);
        return data;
    }

    public Integer getRegisterSum(String subSystemSign, String currentDay) {
        try {
            CustUnifyRegisterStatisticPo po = new CustUnifyRegisterStatisticPo();
            po.setSubSystemSign(subSystemSign);
            po.setDate(currentDay);
            po.setType(1);
            List<CustUnifyRegisterStatisticPo> list = registerStatisticMapper.select(po);
            if (list.size() == 0) {
                return 0;
            } else {
                return list.get(0).getRegisterNum();
            }
        } catch (DataAccessException e) {
            log.info("查询cust_unify_register_statistic报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public JSONObject countLoginFlow(CountLoginFlowRo ro) {
        JSONObject data = new JSONObject();
        data.put("productCode", ro.getProductCode());
        data.put("productId", ro.getProductId());
        CustUnifyLoginStatisticPo po = new CustUnifyLoginStatisticPo();
        String currentDay = new SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
        String yesterDay = CustomerUtils.getPastDate(1, currentDay);
        po.setDate(yesterDay);
        List<CustUnifyLoginStatisticPo> pos = loginStatisticMapper.select(po);
        JSONArray tables = new JSONArray();
        JSONObject table = new JSONObject();
        table.put("tableKey", "countType");
        table.put("tableName", "登陆流水统计");
        table.put("columns", "系统来源,总数,成功条数,失败条数");
        if (pos != null && pos.size() > 0) {
            List<List<Object>> dataList = new ArrayList<>();
            for (CustUnifyLoginStatisticPo custUnifyLoginStatisticPo : pos) {
                List<Object> objectList = new ArrayList<>();
                objectList.add(custUnifyLoginStatisticPo.getSubSystemSign());
                objectList.add(custUnifyLoginStatisticPo.getSum().toString());
                objectList.add(custUnifyLoginStatisticPo.getSuccessNum().toString());
                objectList.add(custUnifyLoginStatisticPo.getFailNum().toString());
                dataList.add(objectList);
            }
            table.put("list", dataList);
            tables.add(table);
        }
        data.put("tables", tables);
        return data;
    }

}
